// 第几节课
var idx = 1;

function sleep(delay) {
    var start = (new Date()).getTime();
    while ((new Date()).getTime() - start < delay) {
        continue;
    }
}

// 隐藏图标
$('.prism-big-play-btn').style.display = 'none'

// 保存进度
// $$('.el-button--danger').length
var saveProcessBtn = $$('.el-button--mini')[1];
var saveProcessTask = setInterval(() => {
    saveProcessBtn.click();
}, 70000)

var btyAry = $$('.el-button');
var _$ = $, doing = false;
var globalTask = setInterval(() => {
    if (doing) {
        return;
    }

    doing = true;
    // 找到按钮
    var lessionBtn;
    btyAry.forEach((btn, index) => {
        if (index === (idx + 2)) {
            lessionBtn = btn;
        }
    })

    let spanText = lessionBtn.childNodes[2].innerText;
    if (spanText === '返回课程列表') {
        console.log('全部播放完毕');
        clearInterval(saveProcessTask);
        clearInterval(globalTask);
        return;
    }
    
    // 选中课程
    lessionBtn.click();

    // 点击播放
    // console.log('点击播放==>未点击');
    sleep(2000);
    _$('.prism-play-btn').click();
    // console.log('点击播放==>已点击');

    // 等待课程播放完
    let lessonTask = setInterval(() => {
        if (_$('.prism-big-play-btn').style.display === 'block') {
            _$('.prism-play-btn').click();
            _$('.prism-big-play-btn').style.display = 'none'
        }
        
        let currntTime = _$('.current-time').innerText;
        let durationTime = _$('.duration').innerText;
        console.info('等待课程播放完: ' + lessonTask + ' 第' + idx + '讲 ' + currntTime + ' => ' + durationTime);
        if (currntTime == durationTime) {
            // 清楚定时任务
            clearInterval(lessonTask);
            // 看完 idx + 1
            idx++;
            doing = false;
            sleep(5000);
        }
    }, 2000);
}, 5000);